﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using V5_Common;
using V5_BLL;
using V5_Model;

namespace V5_EShop._Template.Default
{
    public partial class Shopping_Order : BasicPage
    {
        public ModelUserToArea area = new ModelUserToArea();

        public int payid = 0, sendid = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            Action = Input.SetString(Request["action"]);
            int pid = Input.SetInt(Request["pid"]);
            if (!this.check_member_login())
            {
                Response.Redirect("/login.aspx?returnurl=" + HTTPS.GetCurrentUrl());
            }
            switch (Action.ToLower().Trim())
            {
                case "del":
                    break;
                default:
                    Bind_rpShoppingList();
                    break;
            }

            //if (!this.IsPostBack)
            {
                int addressid = Input.SetInt(Request["addressid"]);
                if (addressid > 0)
                {
                    area = new BLLUserToArea().GetModel(addressid);
                }
            }
            payid = Input.SetInt(Request["payid"]);
            sendid = Input.SetInt(Request["sendid"]);
        }

        private void Bind_Delete(int proid)
        {
            if (proid > 0)
            {
                ModelProduct model = new BLLProduct().GetModel(proid, true);
                if (model != null)
                {
                    DataTable dtProducts = null;
                    if (Session["dtProducts"] != null)
                    {
                        dtProducts = (DataTable)Session["dtProducts"];
                    }
                    else
                    {
                        Response.Redirect(HTTPS.ComeUrl);
                    }

                    for (int i = 0; i < dtProducts.Rows.Count; i++)
                    {
                        if (Convert.ToInt32(dtProducts.Rows[i]["pid"]) == proid)
                        {
                            dtProducts.Rows[i].Delete();
                        }
                    }
                    dtProducts.AcceptChanges();
                    Session["dtProducts"] = dtProducts;//添加完毕后更新session
                    Repeater rp = (Repeater)this.FindControl("rpShoppingList");
                    if (rp != null)
                    {
                        rp.DataSource = dtProducts;
                        rp.DataBind();
                    }
                }
            }
        }

        public string Product_Count = "0", Product_Jifen = "0", Product_LoseJifen = "0", Product_Money = "0";
        private void Bind_rpShoppingList()
        {
            DataTable dtProducts = null;
            if (Session["dtProducts"] != null)
            {
                dtProducts = (DataTable)Session["dtProducts"];
                Product_Count = dtProducts.Rows.Count.ToString();
                int m6 = 0;
                //产品总金额
                for (int i = 0; i < dtProducts.Rows.Count; i++)
                {
                    m6 += (Input.SetInt(dtProducts.Rows[i]["prototalprice"]));
                }
                Product_Money = m6.ToString();
                //产品积分
                Product_Jifen = m6.ToString();
                this.rpShoppingList.DataSource = dtProducts;
                this.rpShoppingList.DataBind();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            this.ibtnGoPaySucc.Click += new ImageClickEventHandler(ibtnGoPaySucc_Click);
            base.OnInit(e);
        }

        void ibtnGoPaySucc_Click(object sender, ImageClickEventArgs e)
        {
            //检查购物车是否为空
            if (Session["dtProducts"] == null)
            {
                Pr.RegClientAlertAndRedirect(this, "购物车没有产品!", HTTPS.ComeUrl);
                return;
            }
            DataTable dt = (DataTable)Session["dtProducts"];
            int m_TotalPrice = 0;//产品总价
            int m_productcount = 0;//产品个数
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                m_TotalPrice = m_TotalPrice + Input.SetInt(dt.Rows[i]["prototalprice"].ToString());
            }
            m_productcount = dt.Rows.Count;

            BLLProductOrder bll = new BLLProductOrder();
            ModelProductOrder model = new ModelProductOrder();
            int OrderID = 0;
            //配送方式
            //送货地址

            //支付方式
            //送货时间
            /**/
            int MemberID = user.ID;//会员ID号
            DateTime OrderTime = DateTime.Now;//订单时间
            string ShipTime = sendid.ToString();//送货时间
            string BuyerName = user.TrueName;//买家用户名
            string BuyerPhone = user.Telephone;//买家电话
            string BuyerEmail = user.UserEmail;//买家Email
            string BuyerAddress = user.Address;//买家地址
            string BuyerPostalcode = user.AreaID.ToString();//邮政编号
            string ReceiverName = area.tousername;//收货人姓名
            string ReceiverPhone = area.tousertelephone;//收货人电话
            string ReceiverEmail = user.UserEmail;//收货人Email
            string ReceiverAddress = area.id.ToString();//配货地址ID号
            string ReceiverPostalcode = area.topostnum;//收货人邮政编号
            string Remark = txtOtherContent.Text;//订单备注
            decimal TotalPrice = m_TotalPrice;//产品总价
            decimal ProductPrice = 20;//产品价格
            decimal CustomItemPrice = 200;//自定义价格
            string Discount = "20%";//折扣
            decimal ShipPrice = 0;//邮费
            decimal AdvancePayment = 100;//高级付款
            int PaymentType = payid;//支付类型
            int ShippingType = sendid;//送货类型
            int Score = m_TotalPrice;//积分
            decimal Weight = 100;//重量
            int Quantity = m_productcount;//个数
            //Response.Write(Input.SetString(Request.Form["fapiao"]));
            int NeedInvoice = 0;//需要发票
            string InvoiceHead = this.txtFaStartTitle.Text;//发票头
            string InvoiceContent = "";//发票头
            if (rbtnfa1.Checked)
            {
                NeedInvoice = 1;
                InvoiceContent = ddl_FaPiaoContent.SelectedValue;
            }
            if (rbtnfa2.Checked)
            {
                NeedInvoice = 0;
                InvoiceContent = "无";
            }


            int IsCancelled = 1;//取消
            int IsConfirmed = 1;//确认
            int PayStatus = 0;//支付状态 0 未支付 1 支付
            int ShippingStatus = 0;//订单状态 0 添加 1 已确认 2 已付款 3已发货 4 已归档 5 取消订单 
            int IsFinished = 0;//完成
            string ManageHistory = "收货";
            int LastModify = 1;
            string OrderNo = bll.ProductOrderNum();//订单号
            string Code = txtOtherContent.Text;//代码
            int IsAgentF = 1;
            string IsAgentFContent = "恩";
            int IsShippingFree = 1;//是否订单免邮费
            //************************************************************************************
            //************************************************************************************
            //开始保存订单 并生产订单
            model.MemberID = MemberID;
            model.OrderTime = OrderTime;
            model.ShipTime = ShipTime;
            model.BuyerName = BuyerName;
            model.BuyerPhone = BuyerPhone;
            model.BuyerEmail = BuyerEmail;
            model.BuyerAddress = BuyerAddress;
            model.BuyerPostalcode = BuyerPostalcode;
            model.ReceiverName = ReceiverName;
            model.ReceiverPhone = ReceiverPhone;
            model.ReceiverEmail = ReceiverEmail;
            model.ReceiverAddress = ReceiverAddress;
            model.ReceiverPostalcode = ReceiverPostalcode;
            model.Remark = Remark;
            model.TotalPrice = TotalPrice;
            model.ProductPrice = ProductPrice;
            model.CustomItemPrice = CustomItemPrice;
            model.Discount = Discount;
            model.ShipPrice = ShipPrice;
            model.AdvancePayment = AdvancePayment;
            model.PaymentType = PaymentType;
            model.ShippingType = ShippingType;
            model.Score = Score;
            model.Weight = Weight;
            model.Quantity = Quantity;
            model.NeedInvoice = NeedInvoice;
            model.InvoiceHead = InvoiceHead;
            //
            model.InvoiceContent = InvoiceContent;
            model.IsCancelled = IsCancelled;
            model.IsConfirmed = IsConfirmed;
            model.PayStatus = PayStatus;
            model.ShippingStatus = ShippingStatus;
            model.IsFinished = IsFinished;
            model.ManageHistory = ManageHistory;
            model.LastModify = LastModify;
            model.OrderNo = OrderNo;
            model.Code = Code;
            model.IsAgentF = IsAgentF;
            model.IsAgentFContent = IsAgentFContent;
            model.IsShippingFree = IsShippingFree;
            OrderID = bll.Add(model);
            //开始清空购物车
            if (Session["dtProducts"] != null)
            {
                //开始添加产品信息
                DataTable dt1 = (DataTable)Session["dtProducts"];
                foreach (DataRow row in dt1.Rows)
                {
                    ModelProductOrderProduct m_ProductOrderProduct = new ModelProductOrderProduct();
                    m_ProductOrderProduct.ID = new BLLProductOrderProduct().GetMaxId();
                    m_ProductOrderProduct.OrderNum = model.OrderNo;//订单号
                    m_ProductOrderProduct.pid = Input.SetInt(row["pid"]);
                    m_ProductOrderProduct.profieldvalues = Input.SetString(row["profieldvalues"]);
                    m_ProductOrderProduct.promarketprice = Input.SetInt(row["promarketprice"]);
                    m_ProductOrderProduct.promemberprice = Input.SetInt(row["promemberprice"]);
                    m_ProductOrderProduct.proname = Input.SetString(row["proname"]);
                    m_ProductOrderProduct.propic = Input.SetString(row["propic"]);
                    m_ProductOrderProduct.proquantity = Input.SetInt(row["proquantity"]);
                    m_ProductOrderProduct.proscore = Input.SetInt(row["proscore"]);
                    m_ProductOrderProduct.prototalprice = Input.SetInt(row["prototalprice"]);
                    new BLLProductOrderProduct().Add(m_ProductOrderProduct);
                }
                //清空购物车
                Session.Remove("dtProducts");
            }
            //发送Email
            Response.Redirect("/Shopping_Clearing.aspx?OrderID=" + OrderID + "&BEmail=" + user.UserEmail);
        }
    }
}
